package com.app.webaiproject.BaseActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

import com.app.webaiproject.R;
import com.app.webaiproject.util.HttpData;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private final HttpPostDataListener listener = result -> {
        if (webView != null) {
            // 转义特殊字符防止 JS 注入
            String escapedResult = result.replace("'", "\\'");
            webView.post(() -> webView.loadUrl("javascript:receiveAIResponse('" + escapedResult + "')"));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWebView();
    }

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    private void initWebView() {
        webView = findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setBackgroundColor(0x00000000);
        webView.loadUrl("file:///android_asset/ai.html");
        webView.addJavascriptInterface(new JsInterface(), "webobj");
        Log.d("WebView", "JS接口已注册");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d("WebView", "页面加载完成");
            }
        });
    }

    // JS 接口类
    private class JsInterface {
        @JavascriptInterface
        public void callAI(String message) {
            String trimmedMessage = message.trim();
            if (!trimmedMessage.isEmpty()) {
                new HttpData(listener).execute(trimmedMessage);
            }
        }
    }

    // 供 AI 工具类回调的接口
    public interface HttpPostDataListener {
        void getDateUrl(String result);
    }
}